package com.example.stag;

import org.jetbrains.annotations.NotNull;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;

@WebServlet("/appraise")
public class AppraiseServlet extends HttpServlet {

    @Override
    public void init() {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
    }

    @Override
    protected void doGet(@NotNull HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter writer = resp.getWriter();
            String id = req.getParameter("id");
            String UserReviews = req.getParameter("userReviews");
            ResultSet resultSet = CommoditySQLOperation.searchById(id);
            if (resultSet.next()) {
                String s = resultSet.getString("UserReviews");
                if (s == null || (s.equals(""))) {
                    CommoditySQLOperation.updateUserReviews(id, UserReviews);
                    writer.println("OK");
                    return;
                }
            }
            writer.println("wrong");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
